package com.wywah.yunduo.security.supports.employee;

import com.wywah.yunduo.security.core.YunduoAuthorizationGrantType;
import com.wywah.yunduo.security.supports.custom.YunduoCustomAuthenticationProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.OAuth2ErrorCodes;
import org.springframework.security.oauth2.core.OAuth2Token;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenGenerator;

import java.util.Map;

public class OAuth2EmployeeAuthenticationProvider extends YunduoCustomAuthenticationProvider<OAuth2EmployeeAuthenticationToken> {

    private Logger logger = LoggerFactory.getLogger(getClass());
    public OAuth2EmployeeAuthenticationProvider(OAuth2AuthorizationService authorizationService,
                                                OAuth2TokenGenerator<? extends OAuth2Token> tokenGenerator,
                                                AuthenticationManager authenticationManager) {
        super(authorizationService, tokenGenerator, authenticationManager);
    }

    public OAuth2EmployeeAuthenticationProvider(HttpSecurity http) {
        super(http);
    }

    @Override
    public boolean supports(Class<?> authentication) {
        boolean supports = OAuth2EmployeeAuthenticationToken.class.isAssignableFrom(authentication);
        logger.debug("supports authentication=" + authentication + " returning " + supports);
        return supports;
    }

    @Override
    public void verifyClient(RegisteredClient registeredClient) {
        assert registeredClient != null;
        if (!registeredClient.getAuthorizationGrantTypes().contains(YunduoAuthorizationGrantType.PASSWORD)) {
            throw new OAuth2AuthenticationException(OAuth2ErrorCodes.UNAUTHORIZED_CLIENT);
        }
    }

    @Override
    public AbstractAuthenticationToken buildToken(Map<String, Object> reqParameters) {
//        String employee = (String) reqParameters.get(OAuth2ParameterNames.USERNAME);
//        String password = (String) reqParameters.get(OAuth2ParameterNames.PASSWORD);
        String employee = (String)reqParameters.get(YunduoAuthorizationGrantType.EMPLOYEE);
        return new UsernamePasswordAuthenticationToken(employee, null);
    }
}
